package cn.com.fattiger.io.bio;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BIOServer {

	private static ExecutorService executorService = Executors
			.newFixedThreadPool(10);
	private static SocketAddress address = new InetSocketAddress(8888);

	public static void main(String[] args) throws Exception {
		ServerSocket server = new ServerSocket(8888);
		server.bind(address);
		while (true) {
			Socket socket = server.accept();
			executorService.submit(new IOHandler(socket));
		}
	}

}

class IOHandler implements Runnable {
	private Socket socket;

	public IOHandler(Socket socket) {
		this.socket = socket;
	}

	public void run() {
		handler(socket);
	}

	private void handler(Socket socket) {
		try {
			InputStream in = socket.getInputStream(); 	// client -> server read
			OutputStream out = socket.getOutputStream();// server -> client write
			byte[] receiveBuffer = new byte[1024];
			int receiveByteCount = 0;
			String receiveMsg = null;
			while ((receiveByteCount = in.read(receiveBuffer)) != -1) {
				receiveMsg = new String(receiveBuffer, 0, receiveByteCount);
				String reponseMsg = "已收到：" + receiveMsg;
				out.write(reponseMsg.getBytes());
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
